package com.beau.controller;

import com.beau.service.CodeService;
import com.beau.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/code")
public class CodeController {

    private final Logger logger = LoggerFactory.getLogger(CodeController.class);
    @Autowired
    private EmailService emailService;

    @Autowired
    private CodeService codeService;

    /**
     * 生成验证码，写入数据库并发送邮件
     * @param email
     * @return
     */
    @GetMapping("create/{email}")
    public Boolean create(@PathVariable("email") String email) {
        logger.info("send email to " + email);
        String code = codeService.genCode();
        long currentTimeStamp = System.currentTimeMillis();
        // 验证码十分钟内有效
        long expireTimeStamp = currentTimeStamp + 10 * 60 * 1000;
        codeService.saveCode(code, email, new Date(currentTimeStamp), new Date(expireTimeStamp));
        return emailService.sendEmail(email, code);
    }

    /**
     * 验证邮箱和验证码是否正确
     * @param email
     * @param code
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable("email") String email, @PathVariable("code") String code) {
        return codeService.validateCode(email, code);
    }

}
